package com.example.photo_album.utils;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class QiniuUtli {

    Configuration cfg = new Configuration(Region.region2());
    UploadManager uploadManager = new UploadManager(cfg);

    @Value("${AccessKey}")
    private String accessKey;
    @Value("${SecretKey}")
    private String secretKey;
    @Value("${bucket}")
    private String bucket;
    @Value("${domainOfBucket}")
    String domainOfBucket;
    @Value("${expireInSeconds}")
    private long expireInSeconds;

    Auth auth = Auth.create(accessKey, secretKey);

    //上传文件，完成后返回图片的URL
    public String upload(MultipartFile multipartFile) throws IOException {
        String token = auth.uploadToken(bucket);
        String fileName = multipartFile.getOriginalFilename();
        InputStream inputStream = multipartFile.getInputStream();
        byte[] byteData = IOUtils.toByteArray(inputStream);
        Response response = uploadManager.put(byteData, fileName, token);
        inputStream.close();
        System.out.println(response.bodyString());
        String result =  response.bodyString();
        return result;
    }

    //通过文件名称获取到文件URL
    public void getImage(String fileName) throws UnsupportedEncodingException {
        String encodedFileName = URLEncoder.encode(fileName, "utf-8").replace("+", "%20");
        String publicUrl = String.format("%s/%s", domainOfBucket, encodedFileName);
        Auth auth = Auth.create(accessKey, secretKey);
        String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
        System.out.println(finalUrl);
    }

    //调用七牛云删除文件API
    public void delImage(String fileName) throws UnsupportedEncodingException {
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(bucket, fileName);
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }
    }

}
